<?php

namespace Wechat\Controller;

use Think\Controller;
use Common\Service\MerchantService;
use Common\Service\MerUserService;
use Common\Service\WxEventCupidUserService;
use Common\Service\WxEventCupidService;
use Common\Service\WxEventCupidAwardService;
use Common\Service\WxEventCupidBeautyService;

class CupidController extends Controller {

  const APPID = 'hfh';
  const TOKEN = 'utqo!u1';

  const SESSION_NAME = 'ccmc_cupid';
  //const GET_USERINFO_URL = 'http://www.luckfu.com/api/v1.0/getuser?';
  //const PAY_POINTS_URL = 'http://www.luckfu.com/api/v1.0/bbexchange?';
  
  const GET_USERINFO_URL = 'http://www.cmccwhwx.com/api/v1.0/getuser?';
  const PAY_POINTS_URL = 'http://www.cmccwhwx.com/api/v1.0/bbexchange?';

  var $redirict_url = 'http://mp.weixin.qq.com/s?__biz=MjM5NTQzNzM1Mw==&mid=214867265&idx=1&sn=7e67b1b9833e31603df68091642560e9#rd';
  
  public function index( $mer_id = 0 , $event_id = 0 ) {
    $user_token = I('get.user_token' , '');
    $user_data = session( self::SESSION_NAME );
    if ( empty($user_data) ) {
      $this->_check_user_info($mer_id , $user_token); //取用户信息
    }
    
    //print_r($user_data);
      
    $mer_data = $this->_check_mer_info($mer_id);  //检查商户信息
    $event_data = $this->_check_event_info($mer_id , $event_id ); //检查活动信息

    //$user_data = session( self::SESSION_NAME );
    //print_r( $user_data );
    //$WxEventCupid = WxEventCupidService::instance();
    //取活动信息
    $url = "/$mer_id/$event_id/" ;
    $data = array(
      'mer_data' => $mer_data ,
      'beauty_url' => U('Wechat/Cupid/beauty/') . $url ,
      'rule_url' => U('Wechat/Cupid/rule/') . $url ,
    );
    
    $data['event_data'] = $event_data ;
    $data['config'] = array(
      'mer_id' => $mer_id ,
      'event_id' => $event_id ,
      'get_award_list_url' => U('Wechat/Cupid/get_award_list'),
      'get_my_award_list_url' => U('Wechat/Cupid/get_my_award_list'),
    );
    $data['param'] = array(
      'award_status' => array(
        1 => '未领取',
        2 => '已领取'
      )
    );
        
    $this->assign($data);
    $this->display();
  }

  /**
   * 获奖名单
   */
  function get_award_list() {
    $get = I('get.');
    $WxEventCupid = WxEventCupidService::instance();
    $WxEventCupidUserService = WxEventCupidUserService::instance();
    
    $config = array(
      'mer_id' => $get['mer_id'],
      'event_type'=> $WxEventCupid->type ,
      'event_id'  => $get['event_id'] ,
      'page'      => $get['page'] ,
      'page_size' => $get['page_size'],
      'point_gt'  => 90 ,
    );
    
    if ( isset( $get['my_award'] ) ) {
      $user_data = session( self::SESSION_NAME );
      if ( !empty( $user_data ) ) {
        $config['user_id'] = $user_data['user_id'];
      } else {
        $this->ajaxReturn(array(
          'rows' => array(),
          'total' => 0 
        ));
      }
    }
    
    $data['rows'] = $WxEventCupidUserService->get_by_cond($config);
    foreach ( $data['rows'] as $key => $val ) {
      $data['rows'][$key]['phone'] = substr($val['phone'], 0 , 3).'****'. substr($val['phone'], 7, 4);
    }
    
    $config['count'] = TRUE ;
    $data['total'] = $WxEventCupidUserService->get_by_cond($config);
    
    $this->ajaxReturn($data);
  }
  
  /**
   * 选择美人页
   * @param type $mer_id
   * @param type $event_id
   */
  function beauty( $mer_id = 0 , $event_id = 0 ) {
    $user_data = session( self::SESSION_NAME );
    if ( empty( $user_data ) ) {
      redirect($this->redirict_url);
      exit();
    }
    
    //print_r( $user_data );
    
    $mer_data = $this->_check_mer_info($mer_id);  //检查商户信息
    $event_data = $this->_check_event_info($mer_id , $event_id ); //检查活动信息
    $url = "/$mer_id/$event_id/" ;
    
    $data['mer_data'] = $mer_data;
    $data['event_data'] = $event_data ;
    $data['index_url'] =  U('Wechat/Cupid/index/') . $url ;
    
    $WxEventCupidBeauty = WxEventCupidBeautyService::instance();
    $data['male_data'] = $WxEventCupidBeauty->get_by_cond(array(
      'gender' => 1 ,
    ));
    
    $data['female_data'] = $WxEventCupidBeauty->get_by_cond(array(
      'gender' => 2 ,
    ));
    
    $data['config'] = array(
      'index_url' => U('Wechat/Cupid/index/') . $url  ,
      'result_url' => U('Wechat/Cupid/result/') . $url  ,
      'test_beauty' => U('Wechat/Cupid/test_beauty') . $url ,
      //'do_beauty' => U('Wechat/Cupid/index') . $url ,
    );
    $this->assign($data);
    $this->display(); 
  }
  
  /**
   * 测算
   * @param type $mer_id
   * @param type $event_id
   */
  function test_beauty( $mer_id = 0 , $event_id = 0 ) {
    $user_data = session( self::SESSION_NAME );
    if ( empty( $user_data ) ) {
      $this->ajaxReturn(ajax_arr('先关注' , FALSE , array(
        'url' => $this->redirict_url 
      )));
    }

    $beauty_id = I('post.beauty_id');
    $WxEventCupid = WxEventCupidService::instance();
    
    $ret = $WxEventCupid->test_beauty( $mer_id , $event_id , $user_data['user_id'] , $beauty_id );
    $this->ajaxReturn($ret);
  }
  
  /**
   * 测算结果页
   * @param type $mer_id
   * @param type $event_id
   * @param type $event_user_id
   */
  function result( $mer_id = 0 , $event_id = 0 , $event_user_id = 0 ) {
    $mer_data = $this->_check_mer_info($mer_id);  //检查商户信息
    $event_data = $this->_check_event_info($mer_id , $event_id ); //检查活动信息
    $url = "/$mer_id/$event_id/" ;  
    
    $data['mer_data'] = $mer_data;
    $data['event_data'] = $event_data ;
    $data['index_url'] =  U('Wechat/Cupid/index/') . $url ;
    $data['rule_url'] = U('Wechat/Cupid/rule/') . $url  . $event_user_id ;
        
    //取中奖信息
    $WxEventCupidUserService = WxEventCupidUserService::instance();
    $data['user_award_data'] = $WxEventCupidUserService->get_by_id($event_user_id , TRUE );
    //print_r( $data['user_award_data'] );

    //取用户信息
    $MerUser = MerUserService::instance();
    $data['user_data'] = $MerUser->get_by_id($data['user_award_data']['user_id']);
    
    $user_data = session( self::SESSION_NAME );
    $data['config'] = array(
      'take_award_url' => U('Wechat/Cupid/take_award_url'),
      'is_login' => empty( $user_data ) ? FALSE : TRUE ,
      'event_user_id' => $event_user_id ,
      'point' => $data['user_award_data']['point'] ,
    );
    
    $data['share'] = array(
      'title' => '帮帮周年庆之月老帮帮来牵线',
      'desc' => $data['user_award_data']['share_text'] ,
      'icon' => U('Public/themes/wechat/cupid/images/share_icon.jpg' , '' , true , true ),
      'url'  => U('Wechat/Cupid/result/', '' , true , true) . "/$mer_id/$event_id/$event_user_id",
    );
    
    $this->assign($data);
    $this->display(); 
    
  }
  
  /**
   * 规则领奖页
   * @param type $mer_id
   * @param type $event_id
   * @param type $event_user_id
   */
  function rule( $mer_id = 0 , $event_id = 0  , $event_user_id = 0 ) {
    $mer_data = $this->_check_mer_info($mer_id);  //检查商户信息
    $event_data = $this->_check_event_info($mer_id , $event_id ); //检查活动信息
    $url = "/$mer_id/$event_id/" ;
    
    $data['mer_data'] = $mer_data;
    $data['event_data'] = $event_data ;
    $data['index_url'] =  U('Wechat/Cupid/index/') . $url ;
    $data['phone'] = '';
    $data['truename'] = '';
        
    //用户信息
    $user_data = session( self::SESSION_NAME );

    $data['config'] = array(
      'event_user_id' => $event_user_id ,
      'is_loggin' => empty( $user_data ) ? FALSE : TRUE ,
      'has_award' => FALSE ,
      'redirect_url' => $this->redirict_url ,
      'take_award_url' => U('Wechat/Cupid/take_award'),
    );
    
    if (!empty( $user_data ) ) {
      //查询是否有未领奖的记录
      $WxEventCupidUser = WxEventCupidUserService::instance();
      $award_data = $WxEventCupidUser->get_by_user( $user_data['user_id'] , 1 , 90 );
      $data['config']['has_award'] = empty( $award_data )? FALSE : TRUE ;
      
      $MerUser = MerUserService::instance();
      $user_info = $MerUser->get_by_id($user_data['user_id']);
      $data['phone'] = $user_info['phone'];
      $data['truename']= $user_info['truename'];
    }
        
    //print_r($data);
    $this->assign($data);
    $this->display(); 
  }
  
  function take_award() {
    $event_user_id= I('post.event_user_id');
    
    $phone    = I('post.phone');
    $truename = I('post.truename') ;
    
    $user_data = session( self::SESSION_NAME );
    $user_id = $user_data['user_id'];
    
    $WxEventCupidUser = M('WxEventCupidUser');
    $WxEventCupidUser->startTrans();
    
    $ret1 = $WxEventCupidUser->where( 'user_id = %d' , $user_id )->save( array(
      'award_status' => 2
    ));
    
    $sql = "update mer_user set truename = '$truename' , phone = '$phone' where id = " . $user_id ;
    $WxEventCupidUser->execute($sql);
    
    if ( $ret1 ) {
      $WxEventCupidUser->commit();
      $this->ajaxReturn(ajax_arr('奖品领取成功' , TRUE ));
    } else {
      $WxEventCupidUser->rollback();
      $this->ajaxReturn(ajax_arr('奖品领取失败,请稍后再试'));
    }
    
  }
    
  
  /**
   * 取用户信息
   * @param type $mer_id
   */
  function _check_user_info($mer_id , $user_token ) {
    //根据user_token取用户信息
    $api_ret = $this->_get_user_info_from_api($user_token);

    //print_r( $api_ret );
    if ( $api_ret['status'] != 1 ) {
      //gameover($api_ret['msg']);
      redirect($this->redirict_url);
      exit();
    }

    $MerUser = MerUserService::instance();
    $user_local_data = $MerUser->get_by_mer_extid($mer_id, $api_ret['uid']);
    
    if ( empty( $user_local_data ) ) {
      //新建用户
      $username = 'cmcc_' . rand_string(12)  ;
      $new_array = array(
        'ext_id'   => $api_ret['uid'],
        'mer_id'   => $mer_id ,
        'phone'    => $api_ret['phone'] ,
        'icon'     => $api_ret['headimgurl'] ,
        'nickname' => empty( $api_ret['nickname']) ? $username : $api_ret['nickname'] ,
        'username' => $username ,
      );
      $user_local_data = $this->_create_cmcc_user($new_array );
    }
    $save_data = array(
      'user_id' => $user_local_data['id'],
      'user_token' => $user_token ,
    );
    
    session( self::SESSION_NAME , $save_data );
  }
    
  /**
   * 
   * @param type $new_user_data
   * @return type
   */
  function _create_cmcc_user( $new_user_data ) {
    $new_user_data['role_id'] = MerUserService::USER_ROLE ;
    $new_user_data['phone_verified'] = 1 ;
    $new_user_data['status'] = MerUserService::STATUS ;
    $new_user_data['password'] = md5('1234') ;
    
    $MerUser = MerUserService::instance();
    $data =  $MerUser->create($new_user_data);  
    if ( !$data['status'] ) {
      gameover('创建用户失败');
    }
    return $data;
  }
  
  
  /**
   * 从api取用户信息
   * @param type $user_token
   */
  function _get_user_info_from_api($user_token) {
    if ( $user_token == 'test' ) {
      return array(
        'uid'         => 232824 ,
        'status'     => 1 ,
        'msg'        => 'ok' ,
        'phone'      => '15926212058' ,
        'nickname'   => 'Em!Ly_小爱' ,
        'headimgurl' => 'http://wx.qlogo.cn/mmopen/SYeWkon6C6IqS50Y2Ov4ft2fOcwQFXIP1iaia70q1ynZTwhOgCh73YYWYeZIJs0wmcUNKrDibia7usE1Cib7rJhZwtQ/96' ,
      ); 
    }
    
    $data = array(
      'appid' => self::APPID ,
      'user_token' => $user_token ,
    );
    
    $send_data = $this->_make_sign($data);
    $send_url = self::GET_USERINFO_URL . http_build_query($send_data);
    
    //echo $send_url ;    
    return $this->_http_get( $send_url );
  }
  
  /**
   * 签名
   * @param array $data
   * @return type
   */
  function _make_sign($data) {
    $data['token'] = self::TOKEN;
    ksort($data);
    $arr = array();
    foreach ( $data as $key => $val ) {
      $arr[] = "$key=" . $val ;
    }
    $string = implode('&', $arr);
    //echo $string . '<br>';
    $data['sign'] = sha1($string);
    unset( $data['token'] );
    return $data;
  }
  
  /**
   * curl get
   * @param type $url
   * @return type
   */
  function _http_get($url) {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_TIMEOUT, 500);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($curl, CURLOPT_URL, $url);
    //优化
    curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array('Expect: '));
    curl_setopt($curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
    $res = curl_exec($curl);
    curl_close($curl);

    //file_put_contents('./Public/tmp/cmcc.txt', date('Y-m-d H:i:s') . ' ' . $res . "\r\n" , FILE_APPEND );
    $ret = json_decode($res, TRUE);
    return $ret;
  }


  function _check_mer_info( $mer_id ) {
    if( empty($mer_id) ) {
      gameover('商户参数错误');
    }

    //取商户信息
    $Merchant = MerchantService::instance();
    $mer_data = $Merchant->get_by_id($mer_id);

    if ( empty( $mer_data ) ) {
      gameover('商户信息错误');
    }
    return $mer_data ;
  }

  function _check_event_info( $mer_id , $event_id ) {
    $WxEventCupid = WxEventCupidService::instance();
    $today = strtotime(date('Y-m-d'));
    $event_data = $WxEventCupid->get_by_id($event_id);
    if ( $mer_id != $event_data['mer_id'] ) {
      gameover('商户没有该活动');
    }
    
    if ( $today < strtotime($event_data['start_time']) ) {
      gameover('活动还未开始');
    }
    
    if ( $today > strtotime($event_data['end_time']) ) {
      gameover('活动已经结束');
    }
    return $event_data ;
  }
  
  
  function test() {
    $this->display();
  }
}
